<?php

declare(strict_types=1);

namespace App\Controller;

use App\Constants\ErrorCode;
use App\Exception\BusinessException;
use App\Library\Common;
use App\Service\FlyShopService;
use App\Service\FlyTopicService;
use App\Service\MomentsApplyService;
use App\Service\MomentService;
use App\Service\QueueService;
use Hyperf\Di\Annotation\Inject;
use Psr\Http\Message\ResponseInterface;
use function Swoole\Coroutine\Http\get;

/**
 * Class MomentsController
 * @package App\Controller
 */
class MomentsController extends AbstractController
{
    /**
     * @Inject
     * @var FlyShopService
     */
    private $shop;

    /**
     * @Inject
     * @var QueueService
     */
    private $queue;

    /**
     * @Inject
     * @var MomentsApplyService
     */
    private $momentsApply;

    /**
     * @Inject
     * @var MomentService
     */
    private $moment;

    /**
     * @Inject
     * @var FlyTopicService
     */
    private $topic;

    /**
     * 获取用户ID
     * @param bool $is_get
     * @return int|ResponseInterface
     */
    public function get_user_id(bool $is_get = false)
    {
        $user_id = (int)$this->request->getHeaderLine('admin_id') ?? 0;
        if (empty($user_id)) {
            if ($is_get) {
                return $this->jsonResponse->success([], '未登录，请先登录');
            }
            throw new BusinessException(ErrorCode::NORMAL_ERROR, '未登录请先登录');
        }
        return $user_id;
    }

    /**
     * 获取商家端动态列表
     * @return ResponseInterface
     */
    public function momentsList(): ResponseInterface
    {
        $user_id = $this->get_user_id(true);
        $get_shop_id = $this->shop->getMyShop($user_id);
        if (empty($get_shop_id)) {
            return $this->jsonResponse->success([], '未获取到店铺信息');
        }
        $shop_id = $get_shop_id['id'];
        $moments_style = $this->request->input('moments_style', 1);
        $moments_style = $moments_style == 1 ? 1 : 2;
        // 店铺
        $has_cert = (int)(in_array($get_shop_id['shop_state'], [1, 2]) || in_array($get_shop_id['food_state'], [1, 2]));
        $builder = $this->moment->getMomentsList($shop_id, $this->request->all(), $has_cert, $moments_style, $user_id,);
        $return = $this->paginate($builder)->toArray();
        foreach ($return['data'] as &$datum) {
            if (!empty($datum['with_curr_applys'])) {
                $datum['with_curr_applys']['files_json_arr'] = empty($datum['with_curr_applys']['files_json']) ? [] : json_decode($datum['with_curr_applys']['files_json'], true);
                $datum['with_curr_applys']['product_json_arr'] = empty($datum['with_curr_applys']['product_json']) ? [] : json_decode($datum['with_curr_applys']['product_json'], true);
            }
        }
        $return['count_stat'] = $this->moment->getStateCount($shop_id, $moments_style);
        $return['status'] = $this->request->input('status', 0);
        return $this->jsonResponse->success($return, 'success!');
    }

    /**
     * 商家发布动态 或 达人发布达人动态
     * @return ResponseInterface
     */
    public function applyMoments(): ResponseInterface
    {
        $user_id = $this->get_user_id();
        $moments_id = (int)$this->request->input('moments_id', 0);
        $moments_style = $this->request->input('moments_style', 1);
        $moments_style = $moments_style == 1 ? 1 : 2;
        $data = $this->moment->verify($user_id, $moments_id, $moments_style);
        $res = $this->moment->applyMoments($data, $user_id, $moments_style);
        return $res ? $this->jsonResponse->success(['applys_id' => $res], 'ok!') :
            $this->jsonResponse->error(ErrorCode::NORMAL_ERROR, '保存失败');
    }

    /**
     * 上下架操作 :is_show =0 撤回上架申请  =1 上架待审核
     * @return ResponseInterface
     */
    public function isShowCheck(): ResponseInterface
    {
        $user_id = $this->get_user_id();
        $moments_id = (int)$this->request->input('moments_id', 0);
        $is_show = (bool)$this->request->input('is_show', 0);
        $cancel_act = $this->request->input('cancel_act');// 下线类型 0下架并编辑 1下架并删除 null:仅上下架
        if (!is_null($cancel_act)) {
            $cancel_act = (bool)$cancel_act;
            if (!$this->moment->isShowCheck($moments_id, $user_id, $is_show, $cancel_act)) {
                return $this->jsonResponse->error(ErrorCode::NORMAL_ERROR, '操作失败');
            }
        } else {
            if (!$this->moment->isShowCheck($moments_id, $user_id, $is_show, null)) {
                return $this->jsonResponse->error(ErrorCode::NORMAL_ERROR, '操作失败2');
            }
        }
        return $this->jsonResponse->success([], '操作成功');
    }

    /**
     * 获取当前申请单信息
     * @return ResponseInterface
     */
    public function getApplyInfos()
    {
        $user_id = $this->get_user_id(true);
        $applys_id = (int)$this->request->input('applys_id', 0);
        return $this->jsonResponse->success($this->momentsApply->getApplyInfos($user_id, $applys_id), 'ok!');
    }

    /**
     * 商家动态详情
     * @return ResponseInterface
     */
    public function details(): ResponseInterface
    {
        $user_id = $this->get_user_id();
        $id = (int)$this->request->input('moments_id', 0);
        $this->queue->moments_view_count($id);
        return $this->jsonResponse->success($this->moment->getMomentsInfo($id, $user_id), 'ok!');
    }

    /**
     * 动态评论
     * @return ResponseInterface
     */
    public function review(): ResponseInterface
    {
        $user_id = $this->get_user_id();
        if (!$this->moment->review($user_id)) {
            return $this->jsonResponse->error(ErrorCode::NORMAL_ERROR, '操作失败');
        }

        return $this->jsonResponse->success([], '操作成功');
    }

    /**
     * 删除评论
     * @return ResponseInterface
     */
    public function reviewDelete(): ResponseInterface
    {
        $user_id = $this->get_user_id();
        $review_id = (int)$this->request->input('review_id', 0);
        if (!$this->moment->reviewDelete($review_id, $user_id)) {
            return $this->jsonResponse->error(ErrorCode::NORMAL_ERROR, '操作失败');
        }
        return $this->jsonResponse->success([], '操作成功');
    }


    /**
     * 用户点赞收藏
     * @return ResponseInterface
     */
    public function userFavorAct(): ResponseInterface
    {
        $user_id = $this->get_user_id();
        $params = $this->request->all();
        $params['user_id'] = $user_id;
        if (!$this->moment->userFavorAct($params)) {
            return $this->jsonResponse->error(ErrorCode::NORMAL_ERROR, '操作失败');
        }
        return $this->jsonResponse->success([], '操作成功');
    }

    /**
     * 达人圈首页
     * @return ResponseInterface
     */
    public function getDrPage(): ResponseInterface
    {
        // 最新发布的两个话题
        $topic_num = (int)$this->request->input('topic_num', 2);
        $topic = $this->topic->getNewestTopic($topic_num);
        // 专题选项卡-默认第一个专题对应文章分页展示
        $special_id = (int)$this->request->input('special_id', 0);
        // 获取专题列表
        $builder = $this->topic->getSpecialDrByID($special_id);
        return $this->jsonResponse->success([
            'topic' => $topic,
            'special' => $this->paginate($builder)
        ], 'success!');
    }

    /**
     * 获取话题动态列表
     * @return ResponseInterface
     */
    public function getTopicList(): ResponseInterface
    {
        $topic_id = (int)$this->request->input('topic_id', 0);
        $builder = $this->topic->getTopicDrByID($topic_id);
        return $this->jsonResponse->success($this->paginate($builder), 'success!');
    }


    /**
     * 达人专题订阅标签
     * @return ResponseInterface
     */
    public function drSubscribe(): ResponseInterface
    {
        $user_id = (int)$this->getAdminId();
        if (empty($user_id)) {
            return $this->jsonResponse->error(ErrorCode::NORMAL_ERROR, '未登录，请先登录');
        }
        $specials = (array)$this->request->input('specials', []);
        $res = $this->topic->specialSubscribe($user_id, $specials);
        if (!$res) {
            return $this->jsonResponse->error(ErrorCode::NORMAL_ERROR, '操作失败');
        }
        return $this->jsonResponse->success([], '操作成功');
    }

    /**
     * 我订阅的达人专题ID
     * @return ResponseInterface
     */
    public function getMyDrTag(): ResponseInterface
    {
        $user_id = (int)$this->getAdminId();
        if (empty($user_id)) {
            return $this->jsonResponse->success([], '未登录请先登录');
        }
        return $this->jsonResponse->success($this->topic->getSubscribed($user_id), '');
    }
}
